﻿/*编写一个订单管理的控制台程序，实现添加订单、删除订单、修改订单、查询订单（按照订单号、商品名称、客户、订单金额等进行查询）功能。
提示：主要的类有Order（订单）、OrderDetails（订单明细），OrderService（订单服务），订单数据可以保存在OrderService中一个List中。在Program里面可以调用OrderService的方法完成各种订单操作。
要求：
（1）使用LINQ实现各种查询功能，查询结果按照订单总金额排序返回。
（2）在订单删除、修改失败时，能够产生异常并显示给客户错误信息。
（3）作业的订单和订单明细类需要重写Equals方法，确保添加的订单不重复，每个订单的订单明细不重复。
（4）订单、订单明细、客户、货物等类添加ToString方法，用来显示订单信息。
（5）OrderService提供排序方法对保存的订单进行排序。默认按照订单号排序，也可以使用Lambda表达式进行自定义排序。*/
using System;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Serialization;
[Serializable]
public class order
{
    public int id { get; set; }
    public string customer { get; set; }
    public orderdetail orderdetail { get; set; }
    public int totalAmount { get; set; }
    public order() { }
    
    public order(int id,string customer,orderdetail detail)
    {
        this.id = id;
        this.customer = customer;
        this.orderdetail=detail;
        this.totalAmount = detail.Amount * detail.quantity;
    }
    public override bool Equals(object obj)
    {
        if(obj is order otherorder)
        {
            return id==otherorder.id && customer==otherorder.customer&&
            orderdetail==otherorder.orderdetail;
        }
        return false;
    }
    public override int GetHashCode()
    {
        return HashCode.Combine(id, customer);
    }
    public override string ToString()
    {
        return $"ID:{id}, customer:{customer}, details:{orderdetail}, totalAmount:{totalAmount}";
    }

}



[Serializable]
public class orderdetail
{
    public int detailId { get; set; }
    public string productName { get; set; }
    public int quantity { get; set; }
    public int Amount { get; set; } 
    public orderdetail() { }
    public orderdetail(int detailId,string productName,int quantity,int amount)
    {
        this.detailId = detailId;
        this.productName = productName;
        this.quantity = quantity;
        this.Amount = amount;
    }
    public override bool Equals(object obj)
    {
        if (obj is orderdetail otherdetail)
        {
            return detailId == otherdetail.detailId &&
                   productName == otherdetail.productName &&
                   quantity == otherdetail.quantity &&
                   Amount == otherdetail.Amount;
        }
            return false;
    }
    public override int GetHashCode()
    {
        return HashCode.Combine(detailId, productName, quantity, Amount);
    }

    public override string ToString()
    {
        return $"Product: {productName},  Quantity: {quantity},  Amount: {Amount}";
    }
}
[Serializable]
public class orderservice
{
    private List<order> orders= new List<order> { new order(2, "li", new orderdetail(2, "胶带", 5, 6)) } ;
    public void export()
    {
        Console.WriteLine("\nserialized as xml:");
        // 注意这里：创建XmlSerializer实例时，传入typeof(List<order>)而不是typeof(order)  
        XmlSerializer serializer = new XmlSerializer(typeof(List<order>));
        using (FileStream fs = new FileStream("s.xml", FileMode.Create))
        {
            // 序列化orders列表  
            serializer.Serialize(fs, this.orders);
        }
        Console.WriteLine("\nserialized as XML:");
        // 读取并打印XML内容  
        Console.WriteLine(File.ReadAllText("s.xml"));
    }
    public void inport()
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<order>));
        using (FileStream fs = new FileStream("s.xml", FileMode.Open))
        {
            List<order> orderstemp = (List<order>)xmlSerializer.Deserialize(fs);
            Console.WriteLine("\nDeserialized from s.xml:");
            foreach (var order in orders)
            {
                if (order != null)
                {
                    Console.WriteLine(order);
                }
            }
        }
    }
    public void addOrder(order order)
    {
        if (orders.Any(o => o.Equals(order)))
        {
            throw new InvalidOperationException("订单已经存在，无法再次创建");
        }
        orders.Add(order);
        sortorder();
    }
    public void printOrder()
    {
        foreach(var order in orders) {
            if (order != null)
            {
                Console.WriteLine(order);
            }
            else
            {
               throw new InvalidOperationException("订单不存在，因此无法打印信息");   
            }
        
        }
    }
    public void deleteorder(int orderid)
    {
        var order=orders.FirstOrDefault(o => o.id==orderid);
        if(order == null) {
            throw new InvalidOperationException("订单没有找到，因此未能删除");
        }
        orders.Remove(order);
    }
    public void updateorder(order order)
    {
        var existorder = orders.FirstOrDefault(o=>o.id==order.id);
        if(existorder == null)
        {
            throw new InvalidOperationException("订单没找到,因此未能更新");
        }
        orders.Remove(existorder);
        orders.Add(order);
        sortorder();
    }
    public List<order> searchorder(Func<order, bool> predicate)
    {
        return orders
            .Where(predicate)
            .OrderByDescending(o => o.totalAmount)
            .ToList();
    }
    public void sortorder(Func<order, int> orderBy = null)
    {
        if (orderBy == null)
        {
            orders.Sort((o1, o2) => o1.id.CompareTo(o2.id));
        }
        else
        {
            orders.Sort((o1, o2) => orderBy(o1).CompareTo(orderBy(o2))); ;
        } 
    }
}
class program
{
    public static void Main()
    {
        order p1 = new order(1,"wang",new orderdetail(1,"剪刀",10,6));
        orderservice orderservice = new orderservice();
        orderservice.addOrder(p1);
        orderservice.printOrder();
        orderservice.export();
        orderservice.inport();
        
    }
}
